package Day11.homework;

import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

//通过Lock锁编写三个线程 让其出现死锁的案例
//提示: 添加3个对象  每个线程 分别锁两个对象
//让其构成一个循环链  相互等待  可以参考 课上的案例
public class ThreeDeadLock {
    ReentrantLock lock1 = new ReentrantLock();
    ReentrantLock lock2 = new ReentrantLock();
    ReentrantLock lock3 = new ReentrantLock();
    public void dead1(){
        String name = Thread.currentThread().getName();
        try {
            lock1.lock();
            System.out.println(name+"获取了lock1的锁,等待lock2的锁");
            Thread.sleep(1000);
            lock2.lock();
            System.out.println(name+"获取了lock1和待lock2的锁");
            lock2.unlock();
            System.out.println(name+"释放了lock2的锁");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            System.out.println(name+"释放了lock1的锁");
            lock1.unlock();
        }
    }
    public void dead2(){
        String name = Thread.currentThread().getName();
        try {
            lock2.lock();
            System.out.println(name+"获取了lock2的锁,等待lock3的锁");
            Thread.sleep(1000);
            lock3.lock();
            System.out.println(name+"获取了lock2和待lock3的锁");
            lock3.unlock();
            System.out.println(name+"释放了lock3的锁");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            System.out.println(name+"释放了lock2的锁");
            lock2.unlock();
        }
    }
    public void dead3(){
        String name = Thread.currentThread().getName();
        try {
            lock3.lock();
            System.out.println(name+"获取了lock3的锁,等待lock1的锁");
            Thread.sleep(1000);
            lock1.lock();
            System.out.println(name+"获取了lock3和待lock1的锁");
            lock1.unlock();
            System.out.println(name+"释放了lock1的锁");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            System.out.println(name+"释放了lock3的锁");
            lock3.unlock();
        }
    }
    public static void main(String[] args) {
        ThreeDeadLock tdl = new ThreeDeadLock();
        new Thread(()->{tdl.dead1();},"线程1").start();
        new Thread(()->{tdl.dead2();},"线程2").start();
        new Thread(()->{tdl.dead3();},"线程3").start();
    }
}
